package com.rzx.service;


import com.google.gson.GsonBuilder;
import com.rzx.mapper.LoginMapper;
import com.rzx.mapper.MessageMapper;
import com.rzx.po.Message;
import com.rzx.po.MessageType;
import com.rzx.po.MyFile;
import com.rzx.po.Staff;
import com.rzx.web.FileUtil;
import com.rzx.websocket.MyWebSocketHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.TextMessage;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Slf4j
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 5)
@Service
public class ChatService {
    @Autowired
    MessageMapper messageMapper;

    @Autowired
    MyWebSocketHandler handler;

    @Autowired
    FileUtil fileUtil;

    public void broadcast(Long uid, String username, String text) throws IOException {
        Message msg = new Message();
        msg.setDate(new Date());
        msg.setFrom(uid);
        msg.setTo(Message.BROADCAST);
        msg.setFromName(username);
        msg.setText("系统广播: " + text);
        messageMapper.insert(msg);
        handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy年MM月dd日 HH:mm").create().toJson(msg)));
    }

    public List<Message> history(Long from, Long to) {
        Message msg = new Message();
        msg.setFrom(from);
        msg.setTo(to);
        msg.setReverse(true);
        return messageMapper.getMessages(msg);
    }

    public Message sendFile(Long uid, String username, Long to, MultipartFile file) {
        Message msg = new Message();
        msg.setDate(new Date());
        msg.setFrom(uid);
        msg.setTo(to);
        msg.setFromName(username);
        msg.setText(file.getOriginalFilename());
        msg.setType(MessageType.FILE);
        msg.setUrl(System.currentTimeMillis() + file.getName());
        messageMapper.insert(msg);
        msg.setId(messageMapper.selectByUrl(msg.getUrl()).getId());
        try {
            handler.sendFile(to, msg, file.getBytes());
            fileUtil.writeFile(msg.getUrl(), file.getBytes());
        } catch (IOException e) {
            log.error("sendFile", e);
        }

        return msg;
    }

    public MyFile getFile(Long id) {
        Message message = messageMapper.select(id);
        if (null == message) {
            return null;
        }
        byte[] bytes = fileUtil.readFile(message.getUrl());
        MyFile file = new MyFile();
        file.setName(message.getText());
        file.setBytes(bytes);
        return file;
    }
}
